using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Controls
{
    public class TextBoxEx : TextBox
    {
        private bool _selectAll;

        static TextBoxEx()
        {
            FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBoxEx), new FrameworkPropertyMetadata(typeof(TextBoxEx)));
        }

        protected override void OnGotFocus(RoutedEventArgs e)
        {
            if (!base.IsLoaded)
            {
                _selectAll = true;
            }
            else
            {
                SelectAll();
            }
            base.OnGotFocus(e);
            base.PreviewMouseDown -= OnPreviewMouseDown;
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.PreviewMouseDown += OnPreviewMouseDown;
            base.OnLostFocus(e);
        }

        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            TextBox textBox = e.Source as TextBox;
            textBox.Focus();
            e.Handled = true;
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.PreviewMouseDown += OnPreviewMouseDown;
            base.Loaded += TextBoxEx_Loaded;
            base.OnInitialized(e);
        }

        private void TextBoxEx_Loaded(object sender, RoutedEventArgs e)
        {
            if (_selectAll)
            {
                _selectAll = false;
                SelectAll();
            }
        }
    }
}
